﻿using BCGPSCommon;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace BCGPSRESTful
{
    /// <summary>
    /// 统一异常处理
    /// </summary>
    public class WebApiExceptionFilterAttribute:ExceptionFilterAttribute
    {
        /// <summary>
        /// 接口统一异常处理
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is ArgumentException)
            {
                var errorMessageDto = new ErrorMessageDto()
                {
                    ErrorCode = "99996",
                    ErrorMessage = context.Exception.Message,
                };
                context.Result = new ObjectResult(errorMessageDto) { StatusCode = 400 };
            }   
            else
            {
                if (context.Exception.InnerException != null)
                {
                    var errorMessageDto = new ErrorMessageDto()
                    {
                        ErrorCode = "99995",
                        ErrorMessage = "似乎登录异常! :"+context.Exception.InnerException.Message,
                    };
                    context.Result = new ObjectResult(errorMessageDto) { StatusCode = 401 };
                }
                else
                {
                    var errorMessageDto = new ErrorMessageDto()
                    {
                        ErrorCode = "99991",
                        ErrorMessage = context.Exception.Message,
                    };
                    context.Result = new ObjectResult(errorMessageDto) { StatusCode = 500 };
                }
            }
            base.OnException(context);
        } 
    }
}
